from rest_framework import viewsets, filters, permissions
from rest_framework.decorators import action
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend
from .models import Todo
from .serializers import TodoSerializer
from drf_spectacular.utils import extend_schema

@extend_schema(tags=['todos'])  # 添加标签
class TodoViewSet(viewsets.ModelViewSet):
    """待办事项视图集"""
    queryset = Todo.objects.all()
    serializer_class = TodoSerializer
    permission_classes = [permissions.IsAuthenticated]  # 只需要认证，不需要管理员权限
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['status', 'priority']
    search_fields = ['title', 'description']
    ordering_fields = ['created_at', 'due_date', 'priority']

    def get_queryset(self):
        """只返回当前用户的待办事项"""
        return self.queryset.filter(user=self.request.user)

    def perform_create(self, serializer):
        """创建时自动设置用户"""
        serializer.save(user=self.request.user)

    @action(detail=False, methods=['get'])
    def statistics(self, request):
        """获取待办事项统计信息"""
        queryset = self.get_queryset()
        total = queryset.count()
        completed = queryset.filter(status='completed').count()
        pending = queryset.filter(status='pending').count()
        
        return Response({
            'total': total,
            'completed': completed,
            'pending': pending,
            'completion_rate': f"{(completed / total * 100):.1f}%" if total > 0 else "0%"
        })
